package service

import (
	"i-search/entity"
	"log"
)

func SearchData() ([]entity.IpDataInfo, error) {
	tables, err := getTables()
	if err != nil {
		return nil, err
	}

	list := make([]entity.IpDataInfo, 0)
	for _, v := range tables {
		sublist, err := queryData(v)
		if err != nil {
			log.Printf("quer table %s error\n", v)
			continue
		}
		list = append(list, sublist...)
	}

	return list, nil
}

func queryData(tableName string) ([]entity.IpDataInfo, error) {
	var list []entity.IpDataInfo
	err := db.Table(tableName).Scopes().Limit(10).Scan(&list).Error
	if err != nil {
		return nil, err
	}

	for i := range list {
		list[i].Table = tableName
	}

	return list, nil
}

func getTables() ([]string, error) {
	var tableNames []string
	err := db.Raw("SHOW TABLES").Scan(&tableNames).Error

	return tableNames, err
}
